/*
 * @lc app=leetcode.cn id=107 lang=java
 *
 * [107] 二叉树的层次遍历 II
 *
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/
 *
 * algorithms
 * Easy (58.84%)
 * Total Accepted:    10K
 * Total Submissions: 17.1K
 * Testcase Example:  '[3,9,20,null,null,15,7]'
 *
 * 给定一个二叉树，返回其节点值自底向上的层次遍历。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 * 
 * 例如：
 * 给定二叉树 [3,9,20,null,null,15,7],
 * 
 * ⁠   3
 * ⁠  / \
 * ⁠ 9  20
 * ⁠   /  \
 * ⁠  15   7
 * 
 * 
 * 返回其自底向上的层次遍历为：
 * 
 * [
 * ⁠ [15,7],
 * ⁠ [9,20],
 * ⁠ [3]
 * ]
 * 
 * 
 */

// class TreeNode {
//       int val;
//       TreeNode left;
//       TreeNode right;
//       TreeNode(int x) { val = x; }
//   }

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        List<TreeNode> currentLayer = new LinkedList<>();
        LinkedList<List<Integer>> answer = new LinkedList<>();
        currentLayer.add(root);
        answer.push(Arrays.asList(root.val));
        while (currentLayer.size() > 0) {
            List<TreeNode> nextLayer = new LinkedList<>();
            List<Integer> numLayer = new LinkedList<>();
            for (TreeNode node : currentLayer) {
                TreeNode left = node.left;
                TreeNode right = node.right;
                if (left != null) {
                    nextLayer.add(left);
                    numLayer.add(left.val);
                }
                if (right != null) {
                    nextLayer.add(right);
                    numLayer.add(right.val);
                }
            }
            if (numLayer.size() > 0) {
                answer.push(numLayer);
            }
            currentLayer = nextLayer;
        }
        return answer;
    }
}

